﻿using UnityEngine;

namespace Utils
{
    /// <summary>
    ///     Mono单例模板
    /// </summary>
    /// <typeparam name="T"></typeparam>
    public abstract class MonoSingleton<T> : MonoBehaviour where T : MonoSingleton<T>
    {
        protected static T MInstance;

        public static T Instance
        {
            get
            {
                if (MInstance == null)
                {
                    MInstance = FindObjectOfType<T>();

                    if (FindObjectsOfType<T>().Length > 1)
                    {
                        Debug.LogWarning("More then 1");
                        return MInstance;
                    }

                    if (MInstance == null)
                    {
                        var instanceName = typeof(T).Name;
                        Debug.LogFormat("Instance Name; {0}", instanceName);

                        var instanceObj = GameObject.Find(instanceName);
                        if (!instanceObj) instanceObj = new GameObject(instanceName);

                        MInstance = instanceObj.AddComponent<T>();
                        DontDestroyOnLoad(instanceObj); // 保证实例不会被释放
                    }
                    else
                    {
                        Debug.LogFormat("Already exist: {0}", MInstance.name);
                    }
                }

                return MInstance;
            }
        }

        protected virtual void OnDestroy()
        {
            MInstance = null;
        }
    }
}